﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TK;

namespace CustomSerializer.Tests
{
    public class TestBase
    {
        protected TK.CustomSerializer ser;
        protected TK.CustomSerializer serCompressed;

        protected void InitSerializer()
        {
            ser = new TK.CustomSerializer(new CustomSerializerSettings(convertBehavior: CustomSerializerConvertError.Throw)
            {
                CompressNames = false
            });

            serCompressed = new TK.CustomSerializer(new CustomSerializerSettings(convertBehavior: CustomSerializerConvertError.Throw)
            {
                CompressNames = true
            });
        }

        protected void TestObject(TK.CustomSerializer serializer, object o)
        {            
            var stm = new MemoryStream();
            serializer.Serialize(stm, o);
            stm.Position = 0;
            Trace.WriteLine(serializer + ", Length = " + stm.Length);
            var result = serializer.Deserialize(stm, o.GetType());
            Assert.IsInstanceOfType(result, o.GetType());
            Assert.IsTrue(compareObjects(o, result));
        }

        bool compareObjects(object source, object target)
        {
            if (source == null && target == null) return true;
            if(source is IComparable) return (source as IComparable).CompareTo(target)==0;
            if (source is Array)
            {
                var a1 = ((Array) source);
                var a2 = ((Array) target);
                for (var i = 0; i < a1.Length; i++)
                    Assert.IsTrue(compareObjects(a1.GetValue(i), a2.GetValue(i)));
            }
            return true;
        }
    }
}